//是否保存学习流水
var playRecordFlow =false;
//视频播放器DOM
var videoPlayerDom = $('#courseVideoPlayer').get(0)
// 视频素材id
var materialId=0;
var currentVideoId ='';
var currentPlayType = '';
var currentcoursePlayTime = '';
/**
 * 加载播放器
 * @param sign 播放数据签名
 * @param typeKey 播放数据签名
 * @param callback 播放回调
 */
function loadPlayData(sign,typeKey,callback) {
    Zepto.ajax({
        url:baseloaction +'/mobile/uc/play/loadPlayData',
        type:'post',
        dataType:'json',
        data:{
            'sign':sign
        },
        success:function (result) {
            var catalog = result.entity;
            var playerUrl = result.player;
            materialId=catalog.materialId
            Zepto(".course-play-btn").addClass("hide");
            playRecordFlow= true;
            var isK96keVideo = result.isK96keVideo;

            play(catalog,playerUrl,isK96keVideo,callback);
        },
        error:function (error) {
            Zepto.toast("系统错误，加载播放数据失败");
        }
    });
}

/**
 * 执行播放
 * @param catalog 目录对象数据
 * @param playerUrl 播放路径
 * @param callback 播放回调
 */
function play(catalog,playerUrl,isK96keVideo,callback) {
    loadHtml(catalog,playerUrl,isK96keVideo,callback);
}


/**
 * 加载播放内容
 * @param catalog 节点目录对象
 * @param playerUrl 播放路径
 * @param callback 播放回调
 */
function loadHtml(catalog,playerUrl,isK96keVideo,callback) {
    var coursePlayRecord = catalog.coursePlayRecord;
    //获取播放课程信息
    var material = catalog.material;
    //清空定时器
    closeTiming();
    //获取正在播放的节点ID
    catalogId = catalog.id;
    //获取正在播放的课程的ID
    playCourseId = catalog.courseId;
    Zepto("#playId").val(catalogId);
    Zepto("#playCourseId").val(playCourseId);
    $("#materialTypeKey").val(catalog.materialTypeKey);
    switch (catalog.materialTypeKey) {
        case 'ARTICLE' :
            var _materialTypeKey = _getSessionStorage('materialTypeKey')

            if((!isEmpty(_materialTypeKey) && _materialTypeKey === 'VIDEO')) {
                //隐藏暂停视频播放器
                videoPlayerDom.style.display = 'none'
                videoPlayerDom.pause()
            }
            if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'AUDIO') {
                if(!isEmpty($('#courseAudioPlayer').get(0))) $('#courseAudioPlayer').get(0).pause()
            }

            if(Zepto("course-play-box.cp-return").length==0){
                var html ="";
                if(GetQueryString("shareKey")==null && GetQueryString("from")==null){

                    html= '<a class="goBack cp-return" href="javascript:window.history.go(-1);">' +
                        '                    <span class="iconfont icon-fanhui"></span>' +
                        '                    </a>';
                }

                /*if(document.getElementById('course-play-box')!=null) {
                    document.getElementById('course-play-box').innerHTML=html;
                }*/
            }
            Zepto('#course-article-container').html(material.articleContext);
            Zepto.popup('.course-article-read-popup');
            var finish = false;
            Zepto('.course-article-read-popup .content').on('scroll', function () {
                if (this.scrollTopMax) {
                    if (this.scrollTop >= (this.scrollTopMax * 0.9)) {
                        finish = true;
                    }
                } else if ((this.scrollTop + this.clientHeight) >= (this.scrollHeight * 0.9)) {
                    finish = true;
                }
                if (finish) {
                    Zepto('.course-article-read-popup .content').unbind('scroll');
                }
            });
            articleStudyTiming = setInterval(function () {
                studyTime++;
            },1000);
            $("#course-article-close").on("click",function(){
                if(studyTime>=catalog.videoDuration){
                    saveCourseLearnFlow(2);
                }else{
                    saveCourseLearnFlow(1);
                }
                var _materialTypeKey = _getSessionStorage('materialTypeKey')
                if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'AUDIO') {
                    //显示音频播放器
                    $('#course-play-box > .course-play__wrap').show();
                    $('#courseAudioPlayer').get(0).pause();
                    $('#course-play-box, .course-play-bg, .course-play-btn').hide();
                    return
                }
                if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'VIDEO') {
                    //显示视频播放器
                    videoPlayerDom.style.display = 'block'
                    videoPlayerDom.pause()
                    $('#course-play-box, .course-play-bg, .course-play-btn').hide()
                    return
                }
            });
            break;
        case 'VIDEO':
            var url ='';
            if(material.playType=='96K' || isK96keVideo){
                var _materialTypeKey = _getSessionStorage('materialTypeKey')
                if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'AUDIO') {
                    $('#course-play-box > .course-play__wrap').remove()
                }
                if(coursePlayRecord){
                    currentcoursePlayTime = coursePlayRecord.duration;
                }else{
                    currentcoursePlayTime =0;
                }
                get96krVideoUrlFn({
                    videoIdCode: material.playUrl,
                    currentcoursePlayTime:currentcoursePlayTime
                })
                _removeSessionStorage('materialTypeKey')
                _setSessionStorage('materialTypeKey', catalog.materialTypeKey)
            }else if(material.playType=='CC'){
                url = playerUrl+ material.playUrl;
            }
            if(material.playType=='96K' || material.playType=='CC' || material.playType=='TT'){
                var script = document.createElement('script');
                var url = playerUrl + '?width=100%&height=100%&videoId=' + material.playUrl
                script.type = 'text/javascript';
                script.src = url;
                if(courseTypeKey=='LIVE'){
                    if(Zepto('#course-play-box').length>0){
                        Zepto('#course-play-box').html('<a class="goBack cp-return" href='+baseloaction+'"/mobile/course/courseList"><span class="iconfont icon-fanhui"></span></a>');
                    }
                    if(videoPlayerDom!=undefined){
                        videoPlayerDom.style.display = 'block'
                        videoPlayerDom.pause()
                    }
                    //修复iOS直播间无法登录
                    if($.device.ios) {
                        _ccFixFn()
                    }
                    Zepto.popup('.course-live-read-popup');
                    var to = playerUrl.indexOf("view.csslcloud.net");
                    if(to!= -1 ){
                        var context = '';
                        context += '<iframe frameborder="0" scrolling="no" seamless width="100%" height="100%" src="'+playerUrl+'"></iframe>';

                        Zepto("#course-live-container").html(context);
                    }else{
                        Zepto("#course-live-container").html(script);
                    }

                }else{
                    //视频
                   if(material.playType=='96K' || material.playType=='TT') {
                        $('#course-play-box > .course-play__wrap').hide()
                        if(!isEmpty($('#courseAudioPlayer').get(0))) $('#courseAudioPlayer').get(0).pause()
                        get96krVideoUrlFn({
                            videoIdCode: material.playUrl
                        })
                    }
                    if(material.playType=='CC') {
                        Zepto('#course-play-box').html(script);
                    }
                }
            }
            break;
        case 'AUDIO':
            if(material.playType=='96K' || isK96keVideo){
                var _materialTypeKey = _getSessionStorage('materialTypeKey')
                if((!isEmpty(_materialTypeKey) && _materialTypeKey === 'VIDEO')) {
                    //隐藏暂停视频播放器
                    videoPlayerDom.style.display = 'none'
                    videoPlayerDom.pause()
                }
                $('#course-play-box, .course-play-bg, .course-play-btn').show()
                //创建音频播放器
                createAudioPlayer("course-play-box",material.playUrl);
                var audioEle = Zepto('#courseAudioPlayer'),
                    audioDom = audioEle.get(0),
                    audioCode = audioEle.attr('videocode');
                if(audioCode) {
                    initAudioPlayer(audioEle,audioDom,audioCode);
                    //初始化音频播放器上下章节切换按钮
                    initAudioBtn(audioDom);
                    if(coursePlayRecord){
                        currentcoursePlayTime = coursePlayRecord.duration;
                    }else{
                        currentcoursePlayTime =0;
                    }
                }
                _removeSessionStorage('materialTypeKey')
                _setSessionStorage('materialTypeKey', catalog.materialTypeKey)
            }else if(material.playType=='CC'){
                var script = document.createElement('script');
                script.type = 'text/javascript';
                url = playerUrl + material.playUrl;
                script.src = url;
                $('#course-play-box').html(script);
            }videoAudioStudyTiming = setInterval(function () {
                studyTime++;
            },1000);
            break;
        case 'LIVE' : //直播跳转页面
            var _materialTypeKey = _getSessionStorage('materialTypeKey')
            if((!isEmpty(_materialTypeKey) && _materialTypeKey === 'VIDEO' && videoPlayerDom !=undefined)){
                //隐藏暂停视频播放器
                videoPlayerDom.style.display = 'none'
                videoPlayerDom.pause()
            }
            if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'AUDIO') {
                if(!isEmpty($('#courseAudioPlayer').get(0))) $('#courseAudioPlayer').get(0).pause()
            }
            //修复iOS直播间无法登录
            if($.device.ios) {
                _ccFixFn()
            }

            Zepto.popup('.course-live-read-popup');
            var context = '';
            context += '<iframe frameborder="0" scrolling="no" seamless width="100%" height="100%" src="'+playerUrl+'"></iframe>';
            Zepto("#course-live-container").html(context);
            liveStudyTiming = setInterval(function () {
                studyTime++;
            },1000);
            Zepto("#course-live-close").on("click",function(){
                if(studyTime>=30){
                    saveCourseLearnFlow(1);
                }
                var _materialTypeKey = _getSessionStorage('materialTypeKey')
                if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'AUDIO') {
                    //显示音频播放器
                    $('#course-play-box > .course-play__wrap').show()
                    $('#courseAudioPlayer').get(0).pause()
                    return
                }
                if(!isEmpty(_materialTypeKey) && _materialTypeKey === 'VIDEO') {
                    //显示视频播放器
                    videoPlayerDom.style.display = 'block'
                    videoPlayerDom.pause()
                    $('#course-play-box, .course-play-bg, .course-play-btn').hide()
                    return
                }
            });
            break;
        default:
            break;
    }
    callback(material);
}

/**
 * 获取视频播放地址
 */
function get96krVideoUrlFn(params) {
    var videoIdCode = params.videoIdCode
    Zepto.ajax({
        url: 'https://v.96koo.net/common/getVideoInfoJsonP?videoId=' + videoIdCode,
        dataType: 'jsonp',
        success: function (data) {
            var videoUrl = data.video_low_url,        //标清
                videoHighUrl = data.video_high_url,   //高清
                sourceDom = $(videoPlayerDom).children('source').get(0);

            $('#course-play-box, .course-play-bg, .course-play-btn').hide()
            videoPlayerDom.style.display = 'block'
            videoPlayerDom.src = videoHighUrl
            //sourceDom.src = videoUrl
            if($.device.ios) {
                videoPlayerDom.addEventListener("canplay",function() {
                    videoPlayerDom.currentTime = params.currentcoursePlayTime;
                });
            }else{
                videoPlayerDom.currentTime = params.currentcoursePlayTime;
            }
            videoPlayerDom.play()
        },
        error: function (err) {
            $.toast("获取播放资源出错，稍后再试试~")
        }
    })
}


$("body").on('click',".goBack",function(){
    saveCourseLearnFlow(1);
});
/**
 * 保存播放记录
 * @param finish 完成状态，1未完成，2已完成
 * @param practice 随堂练习分数
 */
function savePlayRecord(finish,practice) {
    //当前正在播放的目录ID
    var playId = Zepto("#playId").val();
    //课程/套餐ID
    var params = {
        'buyCourseId':courseId,
        'courseId':playCourseId,
        'catalogId':playId,
        'finish':finish,
        'practice':practice,
        'duration':studyTime
    };
    params = JSON.stringify(params);
    Zepto.ajax({
        url:baseloaction +'/mobile/uc/course/play/record/savePlayRecord',
        type:'post',
        dataType:'json',
        data:params,
        contentType: 'application/json;charset=utf-8',
        success:function (result) {
            if(result.success==true){

            }else{
                //Zepto.toast(result.message);
            }
        },
        error:function (error) {
            Zepto.toast("系统错误，保存播放记录失败");
        }
    });
}

/**
 *
 */
if(videoPlayerDom!=undefined){
    videoPlayerDom.addEventListener("timeupdate",function(){
        studyTime = Math.floor(videoPlayerDom.currentTime);
    });
}

/*
* 播放完成回调
*/
if(videoPlayerDom!=undefined){
    videoPlayerDom.addEventListener("ended",function(){
        if(courseTypeKey!="LIVE" ){
            autoOpenExerciseConfirm($("#playId").val(),2);
        }
        saveCourseLearnFlow(2);
    });
}

//播放的时长（单位/秒）
var studyTime = 0;
//文章定时器
var articleTiming = null;
//视频、音频定时器
var videoAudioTiming = null;
//文章学习定时器
var articleStudyTiming = null;
//直播学习定时器
var liveStudyTiming = null;
//视频、音频学习定时器
var videoAudioStudyTiming = null;


/**
 * 清空定时器
 */
function closeTiming() {
    studyTime = 0;
    if(articleTiming !=null){
        window.clearInterval(articleTiming);
        articleTiming = null;
    }
    if(videoAudioTiming !=null){
        window.clearTimeout(videoAudioTiming);
        videoAudioTiming = null;
    }
    if(liveStudyTiming !=null){
        window.clearInterval(liveStudyTiming);
        liveStudyTiming = null;
    }
    if(articleStudyTiming !=null){
        window.clearInterval(articleStudyTiming);
        articleStudyTiming = null;
    }
    if(videoAudioStudyTiming !=null){
        window.clearInterval(videoAudioStudyTiming);
        videoAudioStudyTiming = null;
    }
};


//=====================音频播放器



/**
 * 创建音频播放器
 */
function  createAudioPlayer(id,playUrl){
    var html = '<section class="course-play__wrap">' ;
    if(GetQueryString("shareKey")==null && GetQueryString("from")==null){

        html+=    '        <header class="bar bar-nav">' +
            '        <a class="button button-link button-nav pull-left goBack mt5" href="javascript:history.back()">' +
            '        <span class="icon icon-left"></span>' +
            '        </a>' +
            '        <h1 class="title" id="audioTitle"></h1>' +
            '        </header>';
    }

    html+= '        <div class="cp-shadow audio-shadow">' +
        '        <div class="box_radio">' + '        <div class="audio_box">' +
        '        <div class="music-nav" id="audio_progress">' +
        '        <!--进度条-->' +
        '        <div class="audio_progress">' +
        '        <span class="audio_line"></span>' +
        '        <span class="audio_blue"></span>' +
        '        <span class="audio_dot"></span>' +
        '        <!--<input type="text" min="0" max="0" step="0.4" value="0" id="scale" >-->\n' +
        '        <span id="scale"></span>' +
        '        </div>' +
        '        <!--当前时间-->' +
        '        <div class="time" id="time_cur" style="float: left;">00:00</div>' +
        '    <!--歌曲时长-->' +
        '    <div class="time" id="time_long" style="float: right;">04:08</div>' +
        '    </div>' +
        '    <!--音乐控制面板-->' +
        '    <span class="audio_btn">' +
        '        <!--快退-->' +
        '        <span class="btn_ff" id="btn_prev"></span>' +
        '        <!--旋转碟片-->' +
        '        <!--<div class="cover" id="play"></div>--%>\n' +
        '        <!--暂停/播放按钮-->' +
        '        <div class="btn_play"></div>' +
        '        <!--快进-->' +
        '        <span class="btn_fr" id="btn_next"></span>' +
        '        </div>\n' +
        '        <audio id="courseAudioPlayer" videocode='+playUrl+' src="" x5-playsinline="" playsinline="" webkit-playsinline="" autoplay="autoplay">' +
        '        手机浏览器太古老了，不支持音频播放器.' +
        '    </audio>' +
        '    </div>' +
        '    </div>' +
        '    </div>' +
        '    </section>'


    document.getElementById(id).innerHTML = html;
}
/**
 * 初始化音频播放器
 * @constructor
 */
function  initAudioPlayer(audioEle,audioDom,audioCode){

    mediaPlayerListener(audioEle, catalogId);
    //加载音频播放数据
    loadData(audioEle,audioDom,audioCode);
}

/**
 * 加载音频播放数据
 * @param audioEle
 * @param audioDom
 * @param audioCode
 */
function loadData(audioEle,audioDom,audioCode){

    var audioDuration = Zepto('#time_long');
    Zepto.ajax({
        url: 'https://v.96koo.net/common/getVideoInfoJsonP?videoId=' + audioCode,
        dataType: 'jsonp',
        success: function (data) {
            videoUrl = data.video_low_url;
            videoHighUrl = data.video_high_url;
            audioUrl = data.mp3_audio_url;
            mp3Url = data.audio_mp3_url;
            fileType = data.file_type;
            videoCover = data.coverImage;
            playerType = data.player_type;
            autoplay = data.automatic;
            totalduration = data.duration;
            defaultBitRate = data.defaultBitRate;

            audioUrl = mp3Url || audioUrl;
            if (data.resultStr) {
                statusChange(catalogId, 'error',audioEle[0].nodeName)
                $.toast(data.resultStr)
                if (audioDom) {
                    audioDom.pause()
                }
                return false
            }
            audioDom.src = audioUrl
            audioDom.play()
            $('aside.course-play-btn').addClass('hide');
            audioDuration.html(time(parseInt(totalduration)))
            var audioTitle = Zepto('#catalogId' + catalogId + ' .chapter-tit').html();
            $('#audioTitle').html(audioTitle);
            // if (audioDom) audioDom.play()
            document.addEventListener("WeixinJSBridgeReady", function () {
                if (audioDom) audioDom.play()
                //console.log('__________正在微信中播放...')
            }, false);

            var audioPro = document.querySelector("#audio_progress")
            var Touch = {}
            audioPro.addEventListener('touchstart', function (ev) {//移动开始
                Touch.startX = ev.changedTouches[0].clientX
            })
            audioPro.addEventListener('touchmove', function (ev) {//移动中
                var widthmax = audioPro.clientWidth
                Touch.endX = ev.changedTouches[0].clientX
                var point = Touch.endX - ((window.innerWidth - widthmax) / 2)
                $('div.btn_play').addClass("btn_pause")
                audioDom.currentTime = point / widthmax * audioDom.duration
            })
            audioPro.addEventListener('touchend', function (ev) {//移动结束
                var widthmax = audioPro.clientWidth
                Touch.endX = ev.changedTouches[0].clientX
                var point = Touch.endX - ((window.innerWidth - widthmax) / 2)
                $('div.btn_play').addClass("btn_pause")
                audioDom.currentTime = point / widthmax * audioDom.duration
            })
        }
    })
}

function statusChange(catalogId, status, type) {
    var btn = $("#playBtn" + catalogId)
    if (status === 'play') {
        $('.player').removeClass('hide')
        $('aside.course-play-btn').addClass('hide');
        btn.find(".play[data-catalogid='"+ catalogId +"']").addClass('hide')
        btn.find(".pause[data-catalogid='"+ catalogId +"']").removeClass('hide')
        if (type == 'AUDIO') {
            $('div.btn_play').addClass("btn_pause")
        }
    } else if (status === 'pause') {
        if (type === 'VIDEO') {
        } else {
            $('div.btn_play').removeClass("btn_pause")
        }
        btn.find(".pause[data-catalogid='"+ catalogId +"']").addClass('hide')
        btn.find(".play[data-catalogid='"+ catalogId +"']").removeClass('hide')
    } else if (status == 'error' || status == 'ended' || status === 'abort') {
        if (type === 'VIDEO') {
            $('.player').addClass('hide')
            $('aside.course-play-btn').removeClass('hide');
        } else {
            $('div.btn_play').removeClass("btn_pause")
        }
        document.removeEventListener('touchstart', touchPlay)
        btn.find(".pause[data-catalogid='"+ catalogId +"']").addClass('hide')
        btn.find(".play[data-catalogid='"+ catalogId +"']").removeClass('hide')
    } else if (status == 'suspend') {
        mediaPlayer.pause()
        mediaPlayer.play()
        btn.find(".pause[data-catalogid='"+ catalogId +"']").addClass('hide')
        btn.find(".play[data-catalogid='"+ catalogId +"']").removeClass('hide')
    }
}
function touchPlay() {
    mediaPlayer.play()
    document.removeEventListener('touchstart', touchPlay)
}

/**
 * 播放器监听事件
 * @param audioEle
 * @param catalogId
 */
function mediaPlayerListener(audioEle, catalogId) {
    mediaPlayer = audioEle.get(0)

    var nodeName = audioEle[0].nodeName

    document.addEventListener('touchstart', touchPlay)
    mediaPlayer.addEventListener('canplay', function () {
        //console.log('__________视频资源合法')
    })
    mediaPlayer.addEventListener('canplaythrough', function () {
        //console.log('__________视频资源已加载时')
    })
    mediaPlayer.addEventListener('play', function () {
        if(videoAudioStudyTiming==null){
            videoAudioStudyTiming = setInterval(function () {
                studyTime ++;
            },1000);
        }
        //console.log('__________2222正在播放中...')
        statusChange(catalogId, 'play', nodeName)
    })
    mediaPlayer.addEventListener('pause', function () {
        closeTiming();
        statusChange(catalogId, 'pause', nodeName)
    })
    mediaPlayer.addEventListener('timeupdate', function () {
        // console.log('__________视频播放中')
        if (nodeName === 'AUDIO') {
            var $timeCur = Zepto('#time_cur'),
                $audioDot = Zepto('.audio_dot'),
                $audioLine = Zepto('.audio_line'),
                wDot = $audioDot.width(),
                $audioBlue = Zepto('.audio_blue'),
                wLine = $audioLine.width()-$audioDot.width()
            var value = Math.round(mediaPlayer.currentTime);
            $timeCur.html(time(mediaPlayer.currentTime));/*加载载歌曲当前播放时间*/
            var leftDot = wLine * value / mediaPlayer.duration;
            /*设置进度条样式*/
            $audioDot.css({ 'left' : leftDot });
            $audioBlue.css({ 'width' : leftDot + wDot / 2 });

        } else {
            statusChange(catalogId, 'play', nodeName)
        }
    });

    mediaPlayer.addEventListener('error', function () {
        statusChange(catalogId, 'error', nodeName);
    });
    mediaPlayer.addEventListener('ended', function () {
        studyTime = mediaPlayer.currentTime;
        //保存学习记录
        saveCourseLearnFlow(2);
        statusChange(catalogId, 'ended', nodeName);
        //清空时长
        closeTiming();
        //检查是否拥有随堂练习有的话弹出
        //根据播放节点的catalogId寻找当前目录
        if(autoOpenExerciseConfirm!=null&&autoOpenExerciseConfirm!=undefined){
            autoOpenExerciseConfirm(catalogId,1);
        }
    });
    mediaPlayer.addEventListener('suspend', function () {
        statusChange(catalogId, 'suspend', nodeName);
    });
    mediaPlayer.addEventListener('abort', function () {
        statusChange(catalogId, 'abort', nodeName);
    });
}


//======================CC开始=======================
var vPlayer = null;
/**
 * H5播放器初始化完成的回调
 * @param obj 视频对象内容
 */
function on_CCH5player_ready(obj) {
    vPlayer = obj;
    if(videoAudioStudyTiming==null){
        videoAudioStudyTiming = setInterval(function () {
            studyTime ++;
        },1000);
    }
}

/**
 *  H5播放器开始播放的回调
 *  该回调的this指向当前vid的video元素
 */
function on_CCH5player_play() {
    console.log('CCH5player_play');
}

/**
 * H5播放器播放完成时的回调
 * 该回调的this指向当前vid的video元素
 */
function on_CCH5player_ended() {
    studyTime = vPlayer.videoElement.currentTime
    //保存学习记录
    saveCourseLearnFlow(2);
    //检查是否拥有随堂练习有的话弹出
    //根据播放节点的catalogId寻找当前目录
    if(autoOpenExerciseConfirm != null && autoOpenExerciseConfirm != undefined){
        autoOpenExerciseConfirm(catalogId,1);
    }
}
//======================CC结束=======================

//=====================保利，开始====================
var polyvObj = null;
// 	播放器数据初始化完毕后，会尝试调用此javascript函数
function s2j_onPlayerInitOver() {
    if(videoAudioStudyTiming==null){
        videoAudioStudyTiming = setInterval(function () {
            studyTime ++;
        },1000);
    }
}
/**
 * 视频播放结束后，会调用此函数
 */
function s2j_onPlayOver() {
    studyTime = polyvObj.j2s_realPlayVideoTime();
    //保存播放记录
    saveCourseLearnFlow(2);
    //清空时长
    closeTiming();
    //检查是否拥有随堂练习有的话弹出
    //根据播放节点的catalogId寻找当前目录
    if(autoOpenExerciseConfirm != null && autoOpenExerciseConfirm != undefined){
        autoOpenExerciseConfirm(catalogId,1);
    }
}
//=====================保利，结束====================

function time(time) {
    if (isNaN(time)) {
        return '00:00';
    }
    var str = '';
    if (time >= 3600) {
        str += hour(time) + ':';
    }
    str += minute(time);
    str += second(time);
    return str;
}

function hour(time) {
    return parseInt(time / 3600);
}

function minute(time) {
    var minute = parseInt(time % 3600 / 60);
    if (minute == 0) return '00:';
    if (minute < 10) return '0' + minute + ':';
    return minute + ':';
}

function second(time) {
    var second = parseInt(time % 60 % 60);
    if (second == 0) return '00';
    if (second < 10) return '0' + second;
    return second;
}

function initAudioBtn(audioDom){
    // 上章节切换
    Zepto('.btn_ff').on('click', function () {//上一章
        if(!isBuy){
            guideBuyCourse("还为购买此课程，建议立即购买此课，学习更多章节！",courseId);
            return;
        }
        var playList = $("#course-catalog-list li a[data-catalog]");
        playList.forEach(function (item, index) {
            if ($(item).data('catalog') == catalogId) {
                if (playList[index - 1]) {
                    Zepto('#course-play-box').html('');
                    if (audioDom) audioDom.pause();
                    goPlay(courseId,playCourseId,$(playList[index - 1]).data('catalog'),playCallbackExposed);
                    return;
                } else {
                    return $.toast("当前节已经为第一节");
                }
            }

        })

    });
    // 下章节切换
    Zepto('.btn_fr').on('click', function () {
        if(!isBuy){
            guideBuyCourse("还为购买此课程，建议立即购买此课，学习更多章节！",courseId);
            return;
        }
        var playList = $("#course-catalog-list li a[data-catalog]");
        playList.forEach(function (item, index) {
            if ($(item).data('catalog') == catalogId) {
                if (playList[index + 1]) {
                    Zepto('#course-play-box').html('');
                    if (audioDom) audioDom.pause();
                    goPlay(courseId,playCourseId,$(playList[index + 1]).data('catalog'),playCallbackExposed);
                    return;
                } else {
                    return $.toast("当前节为最后一节");
                }
            }

        })
    });
    //初始化音频播放器播放按钮
    Zepto('div.btn_play').on('click', function () {
        control(this);
        return;
    });
}
//播放暂停音频
function control(obj) {
    var audio = document.getElementById('courseAudioPlayer');
    if (audio !== null) {
        if (audio.paused) {
            audio.currentTime = currentcoursePlayTime;
            audio.play();// 播放
            Zepto(obj).addClass('btn_pause');
        } else {
            audio.pause();// 暂停
            Zepto(obj).removeClass('btn_pause');
        }
    }
};
//=====================音频播放器


//保存课程学习流水
function saveCourseLearnFlow(finish){
    if(playRecordFlow) {
        //当前正在播放的目录ID
        var playId = Zepto("#playId").val();
        var materialTypeKey = $("#materialTypeKey").val();
        //课程/套餐ID
        if (!(studyTime >= 30)&&finish==1) {
            return;
        }
        var params = {
            'buyCourseId':courseId,
            'courseId':playCourseId,
            'catalogId':playId,
            'duration':studyTime,
            'materialTypeKey':materialTypeKey,
            'finish':finish,
            "materialId":materialId
        };
        params = JSON.stringify(params);
        $.ajax({
            url:baseloaction +'/mobile/uc/course/play/Flow/savePlayRecordFlow',
            type:'post',
            dataType:'json',
            data:params,
            async:false,
            contentType: 'application/json;charset=utf-8'
        });
        closeTiming();
        playRecordFlow =false;
    }
}

window.addEventListener('pagehide', function () {
    $.ajaxSettings.async = false;
    saveCourseLearnFlow(1);

});

window.onunload = function () {

    saveCourseLearnFlow(1);
}

//修复iOS进入直播间无法登录
function _ccFixFn() {
    var cookieName = '_csslcloud_fix';
    var cookieValue = '';
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(cookieName + '=');
        if (c_start != -1) {
            c_start = c_start + cookieName.length + 1;
            var c_end = document.cookie.indexOf(';', c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            cookieValue = document.cookie.substring(c_start, c_end);
        }
    }

    if (!cookieValue) {
        cookieValue = '_fix';
        document.cookie = cookieName + '=' + cookieValue + ';';
        window.location.replace('//view.csslcloud.net/html/_fix_.html?u=' + encodeURIComponent(window.location.href));
    }
}